package com.biz.primus.ms.sms.service.checker;

import com.biz.primus.model.misc.enums.ApiExceptionType;
import com.biz.primus.model.misc.exception.ApiException;
import com.biz.primus.model.misc.vo.ChannelBasedAuth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * @author yanweijin
 * @date 2017/6/14
 */
@Component
public class RepeatRequestChecker extends SendCheckerAdapter {

	@Autowired
	private ShardedJedisPool jedisPool;

	private String repeatRequestRecordKey = "cmp:request:";

	@Override
	public void check(ChannelBasedAuth cba) throws ApiException {
		if(StringUtils.isBlank(cba.getRequestId())){
			throw new ApiException(ApiExceptionType.REQUEST_ID_IS_EMPTY);
		}
		String key = getRedisKey(cba.getChannelCode(),cba.getRequestId());
		try (ShardedJedis jedis = jedisPool.getResource()){
			Long result = jedis.setnx(key, "1");
			if(result==0){
				throw new ApiException(ApiExceptionType.REPEAT_REQUEST);
			}
			jedis.expire(key,3600);
		}
	}

	@Override
	public void afterException(ChannelBasedAuth cba, Exception e) {
//		String key = getRedisKey(cba.getChannelCode(),cba.getRequestId());
//		if(e instanceof ApiException){
//			try (Jedis jedis = jedisPool.getResource()){
//				jedis.del(key);
//			}
//		}
	}

	private String getRedisKey(String channelCode, String requestId){
		return repeatRequestRecordKey + channelCode +":"+requestId;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE+10;
	}
}
